﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using System.Diagnostics;

namespace Member
{
    public partial class Member : Form
    {

        private String str_get_all_customer = "Select card_id, full_name, point, phone, birthday, address, is_vip, join_date, expire_date from CUSTOMER";
        private MySqlLocal mysqllocal = new MySqlLocal();
        private MySqlServer mysqlserver = new MySqlServer();

        public enum VipType
        {
            Normal = 0,
            Vip6Month,
            Vip1Year,
            VipForever,
        }

        public Member()
        {
            InitializeComponent();
            cb_SearchType.SelectedIndex = 0;

            txt_card_id.KeyPress += txt_card_id_KeyPress;
            txt_card_point.KeyPress += txt_card_point_KeyPress;
            dgvListMember.SelectionChanged += dgvListMember_SelectionChanged;
            tb_Search.KeyPress += tb_Search_KeyPress;
            cb_card_type.SelectedIndexChanged += cb_card_type_SelectedIndexChanged;
            cb_SearchType.KeyPress += cb_SearchType_KeyPress;
            this.ActiveControl = tb_Search;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (checkSerial() == false)
            {
                //MessageBox.Show("Cannot connect to server.  Contact administrator");
                //Application.Exit();
                //return;
            }
            Process[] pname = Process.GetProcesses();
            var xamppProc = (from p in pname
                             where p.ProcessName.Contains("xampp-control")
                             select p).ToList();

            if (xamppProc.Count == 0)
            {
                System.Diagnostics.Process.Start(@"C:\xampp\xampp-control.exe");
            }
        }

        void cb_SearchType_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((Keys)e.KeyChar == Keys.Enter)
                this.ActiveControl = tb_Search;
        }


        void tb_Search_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((Keys)e.KeyChar == Keys.Enter)
                if (tb_Search.Text != "")
                    SearchCustomer();
        }

        void cb_card_type_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (Util.IsValidDateFormat(txt_card_join_date.Text))
            {
                DateTime dt = DateTime.Now;
                switch (cb_card_type.SelectedIndex)
                {
                    case 1:
                        dt = dt.AddMonths(6);
                        break;
                    case 0:
                    case 2:
                        dt = dt.AddYears(1);
                        break;
                    case 3:
                        dt = dt.AddYears(80);
                        break;
                }
                txt_card_expire_date.Text = dt.Year.ToString() + "/" + dt.Month.ToString() + "/" + dt.Day.ToString();
            }
        }

        void dgvListMember_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                int i = dgvListMember.CurrentCell.RowIndex;
                if (dgvListMember.RowCount == 0) return;
                if (dgvListMember.ColumnCount == 0) return;
                //if (i >= 0)
                //{
                    
                //}
                //else
                //{
                //    btCopy.Enabled = false;
                //    btAddPoint.Enabled = false;
                //}

                string card_id = dgvListMember[0, i].Value.ToString();
                string name = dgvListMember[1, i].Value.ToString();
                string point = dgvListMember[2, i].Value.ToString();
                string phone = dgvListMember[3, i].Value.ToString();
                string birthday = dgvListMember[4, i].Value.ToString();
               
                string address = dgvListMember[5, i].Value.ToString();
                int vip = int.Parse(dgvListMember[6, i].Value.ToString());
                string join_date = dgvListMember[7, i].Value.ToString();
                string expire_date = dgvListMember[8, i].Value.ToString();

                txt_card_id.Text = card_id;
                txt_customer_name.Text = name;
                txt_customer_phone.Text = phone;
                txt_customer_address.Text = address;
                txt_card_point.Text = point;
                cb_card_type.SelectedIndex = vip;

                txt_card_join_date.Text = DateTime.Parse(join_date).Year + "/" + DateTime.Parse(join_date).Month + "/" + DateTime.Parse(join_date).Day;
                txt_card_expire_date.Text = DateTime.Parse(expire_date).Year + "/" + DateTime.Parse(expire_date).Month + "/" + DateTime.Parse(expire_date).Day;
                txt_customer_birthday.Text = DateTime.Parse(birthday).Year + "/" + DateTime.Parse(birthday).Month + "/" + DateTime.Parse(birthday).Day;
                if (txt_customer_birthday.Text == "1/1/1")
                    txt_customer_birthday.Text = "";
                
                if (txt_card_id.Text != "")
                {
                    btt_customer_update.Enabled = true;
                    btAddPoint.Enabled = true;
                    btCopy.Enabled = true;
                    btReNew.Enabled = true;
                    enableInput();
                }
            }
            catch (Exception ex)
            {
                btCopy.Enabled = false;
                btAddPoint.Enabled = false;
                btReNew.Enabled = false;
                MessageBox.Show(ex.Message);
            }
        }

        void txt_card_point_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsNumber(e.KeyChar) && !char.IsControl(e.KeyChar))
                e.Handled = true;
        }

        void txt_card_id_KeyPress(object sender, KeyPressEventArgs e)
        {
            if(!char.IsNumber(e.KeyChar) && !char.IsControl(e.KeyChar))
                e.Handled = true;
        }

        private void refreshDgvAfterUpdate()
        {
            dgvListMember.DataSource = mysqlserver.ExecuteQuery("Select card_id, full_name, point, phone, birthday, address, is_vip, join_date, expire_date from CUSTOMER where card_id='" + txt_card_id.Text + "'");
        }

        private void LoadCustomerToDgv()
        {
            var source = mysqlserver.ExecuteQuery(str_get_all_customer);
            if (source == null)
                dgvListMember.DataSource = mysqllocal.ExecuteQuery(str_get_all_customer);
            else dgvListMember.DataSource = source;
        }

        private void SearchCustomer()
        {
            try
            {
                if (tb_Search.Text.Trim() == "")
                    return;
                DataTable dt = null;
                if (mysqlserver.isConnectAvailable())
                {
                    if (cb_SearchType.SelectedIndex == 0)
                    {
                        dt = mysqlserver.ExecuteQuery("Select card_id, full_name, point, phone, birthday, address, is_vip, join_date, expire_date from CUSTOMER where 1 and card_id LIKE '%" + tb_Search.Text + "%'");
                    }
                    else if (cb_SearchType.SelectedIndex == 1)
                    {
                        dt = mysqlserver.ExecuteQuery("Select card_id, full_name, point, phone, birthday, address, is_vip, join_date, expire_date from CUSTOMER where 1 and full_name LIKE '%" + tb_Search.Text + "%'");
                    }
                    else if (cb_SearchType.SelectedIndex == 2)
                    {
                        dt = mysqlserver.ExecuteQuery("Select card_id, full_name, point, phone, birthday, address, is_vip, join_date, expire_date from CUSTOMER where 1 and phone LIKE '%" + tb_Search.Text + "%'");
                    }
                    if (dt != null)
                        dgvListMember.DataSource = dt;
                }
                else 
                {
                    if (mysqllocal.isConnectAvailable())
                    {
                        if (cb_SearchType.SelectedIndex == 0)
                        {
                            dt = mysqllocal.ExecuteQuery("Select card_id, full_name, point, phone, birthday, address, is_vip, join_date, expire_date from CUSTOMER where 1 and card_id LIKE '%" + tb_Search.Text + "%'");
                        }
                        else if (cb_SearchType.SelectedIndex == 1)
                        {
                            dt = mysqllocal.ExecuteQuery("Select card_id, full_name, point, phone, birthday, address, is_vip, join_date, expire_date from CUSTOMER where 1 and full_name LIKE '%" + tb_Search.Text + "%'");
                        }
                        else if (cb_SearchType.SelectedIndex == 2)
                        {
                            dt = mysqllocal.ExecuteQuery("Select card_id, full_name, point, phone, birthday, address, is_vip, join_date, expire_date from CUSTOMER where 1 and phone LIKE '%" + tb_Search.Text + "%'");
                        }
                        if (dt != null)
                            dgvListMember.DataSource = dt;
                    }
                    else MessageBox.Show("please start Xampp on your computer");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private bool checkSerial()
        {
            string serial = Util.GetAllDiskDrives();
            if (serial != "")
            {
                DataTable dt = mysqlserver.ExecuteQuery("Select name,serial,access from USER Where serial='" + serial + "'");
                if (dt.Rows.Count > 0)
                {
                    if (int.Parse(dt.Rows[0]["access"].ToString()) == 1)
                    {
                        Global.userName = dt.Rows[0]["name"].ToString();
                        Global.hardDiskSerial = dt.Rows[0]["serial"].ToString();
                        Global.isAccess = true;
                        return true;
                    }
                }
                else
                {
                    mysqlserver.ExecuteNonQuery("Insert Into USER (name, serial, access) VALUES ('', '" + serial + "', 'false')");
                }
            }
            Global.isAccess = false;
            return false;
        }

        private void Cancel()
        {
            resetInput();
            disbleInput();
            dgvListMember.Enabled = true;
            dgvListMember.Visible = true;
            tb_Search.Enabled = true;
            btt_customer_new.Enabled = true;
        }

        private void enableInput()
        {
            txt_customer_name.Enabled = true;
            txt_card_point.Enabled = true;
            txt_customer_phone.Enabled = true;
            txt_customer_birthday.Enabled = true;
            txt_customer_address.Enabled = true;
            cb_card_type.Enabled = true;
            txt_card_join_date.Enabled = true;
            txt_card_expire_date.Enabled = true;
        }

        private void disbleInput()
        {
            txt_card_id.Enabled = false;
            txt_customer_name.Enabled = false;
            txt_card_point.Enabled = false;
            txt_customer_phone.Enabled = false;
            txt_customer_birthday.Enabled = false;
            txt_customer_address.Enabled = false;
            cb_card_type.Enabled = false;
            txt_card_join_date.Enabled = false;
            txt_card_expire_date.Enabled = false;
        }

        private void resetInput()
        {
            txt_card_id.Text = "";
            txt_customer_name.Text = "";
            txt_card_point.Text = "";
            txt_customer_phone.Text = "";
            txt_customer_birthday.Text = "";
            txt_customer_address.Text = "";
            cb_card_type.SelectedIndex = -1;
            txt_card_join_date.Text = "";
            txt_card_expire_date.Text = "";
        }

        private void Update_Member()
        {
            string card_id = txt_card_id.Text;
            string full_name = txt_customer_name.Text;
            string point = txt_card_point.Text;
            string phone = txt_customer_phone.Text;
            string birthday = txt_customer_birthday.Text;
            string address = txt_customer_address.Text;
            int card_type = cb_card_type.SelectedIndex;
            string join_date = txt_card_join_date.Text;
            string expire_date = txt_card_expire_date.Text;
            //check input
            if (full_name == "" || point == "" || card_type < 0 || join_date == "" || expire_date == "")
            {
                MessageBox.Show("Missed customer's informations");
                return;
            }
            if (!Util.IsValidDateFormat(join_date) || !Util.IsValidDateFormat(expire_date) || (birthday != "" && !Util.IsValidDateFormat(birthday)))
            {
                MessageBox.Show("Please input correct format 'year/month/day'");
                return;
            }
            else
            {
                if (DateTime.Parse(expire_date) < DateTime.Parse(join_date))
                {
                    MessageBox.Show("Day expire must larger than Day join");
                    return;
                }
            }
            //
            string query = @"Update CUSTOMER Set full_name='" + full_name + "', point='" + point + "', phone='" + phone + "', birthday='" + birthday + "', address='" + address + "', is_vip='" + card_type + "', join_date='" + join_date + "', expire_date='" + expire_date + "' Where card_id='" + card_id + "'";
            if (mysqlserver.ExecuteNonQuery(query) > 0)
            {
                MessageBox.Show("Update successful");
                refreshDgvAfterUpdate();
            }
        }

        private void reNewMember()
        {
            string card_id = txt_card_id.Text;
            string expire_date = DateTime.Now.AddYears(1).Year + "/" + DateTime.Now.AddYears(1).Month + "/" + DateTime.Now.AddYears(1).Day;
            string query = @"Update CUSTOMER Set  point='" + 0 + "', is_vip='" + 0 + "', expire_date='" + expire_date + "' Where card_id='" + card_id + "'";
            if (mysqlserver.ExecuteNonQuery(query) > 0)
            {
                MessageBox.Show("Renew successful");
                refreshDgvAfterUpdate();
            }
        }

        private void copyRow()
        {
            int index = dgvListMember.CurrentCell.RowIndex;
            if (index >= 0)
            {
                string birthday = dgvListMember[4, index].Value.ToString();
                string join_date = dgvListMember[7, index].Value.ToString();
                string expire_date = dgvListMember[8, index].Value.ToString();

                join_date = DateTime.Parse(join_date).Year + "/" + DateTime.Parse(join_date).Month + "/" + DateTime.Parse(join_date).Day;
                expire_date = DateTime.Parse(expire_date).Year + "/" + DateTime.Parse(expire_date).Month + "/" + DateTime.Parse(expire_date).Day;
                birthday = DateTime.Parse(birthday).Year + "/" + DateTime.Parse(birthday).Month + "/" + DateTime.Parse(birthday).Day;
                if (birthday == "1/1/1")
                    birthday = "";
                string s = dgvListMember[0, index].Value + "|" + dgvListMember[1, index].Value + "|" + dgvListMember[2, index].Value + "|" + dgvListMember[3, index].Value + "|" + dgvListMember[6, index].Value + "|" + birthday + "|" + join_date + "|" + expire_date;
                Clipboard.SetText(s);
            }
        }

        private void showFormAddPoint()
        {
            if (dgvListMember.RowCount <= 0)
                return;
            int index = dgvListMember.CurrentCell.RowIndex;
            if (index >= 0)
            {
                string cardId = dgvListMember[0, index].Value.ToString();
                string name = dgvListMember[1, index].Value.ToString();
                int point = int.Parse(dgvListMember[2, index].Value.ToString());
                DateTime expireDate = DateTime.Parse(dgvListMember[8, index].Value.ToString());
                int vipType = 0;// int.Parse(dgvListMember[4, index].ToString());
                AddPointFrm add = new AddPointFrm(cardId, name, point, vipType, expireDate);
                add.ShowDialog();
                if(add.updateOk)
                    refreshDgvAfterUpdate();
            }
        }


        private void btt_customer_new_Click(object sender, EventArgs e)
        {
            AddMemberFrm addFrm = new AddMemberFrm();
            addFrm.ShowDialog();
        }

        private void btt_customer_update_Click(object sender, EventArgs e)
        {
            Update_Member();
        }

        private void bt_Search_Click(object sender, EventArgs e)
        {
            SearchCustomer();
        }

        private void btCopy_Click(object sender, EventArgs e)
        {
            copyRow();
        }

        #region shortcut key method
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == (Keys.Control | Keys.C))
            {
                copyRow();
                return true;
            }
            else if (keyData == Keys.Add)
            {
                showFormAddPoint();
                return true;
            }
            else if(keyData == (Keys.Control | Keys.S))
            {
                this.ActiveControl = cb_SearchType;
                cb_SearchType.DroppedDown = true;
            }
            return base.ProcessCmdKey(ref msg, keyData);

        }
        #endregion

        private void btAddPoint_Click(object sender, EventArgs e)
        {
            showFormAddPoint();
        }

        private void btReNew_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("This action will reset customer's points to 0\n\t Do you want continues ?", "ReNew", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                reNewMember();
            }
        }

    }
}
